<template>
	<div class="buy">
		<header>
			<webHader :title="t('coursePay.title')" :crumbs="t('coursePay.crumbs')" :backgroundImageUrl="headerBg" />
		</header>
		<div class="content" v-loading="loading">
			<div class="content_detail">
				<div class="title">{{ t('courseBuy.title') }}</div>
				<div class="main">
					<!-- 左侧订单信息 -->
					<div class="order-info">
						<!-- 选择学员 -->
						<div class="section">
							<div class="section-title-row">
								<div class="section-title">{{ t('courseBuy.selectStudent.title') }}</div>
								<el-button :icon="User" @click="handleShowStudents">
									{{ t('courseBuy.selectStudent.button') }}
								</el-button>
							</div>

							<!-- <div class="student-list">
                <div
                  v-for="student in selectedStudents"
                  :key="student.id"
                  class="student-item"
                  style="margin-bottom: 18px"
                >
                  {{ student.nameC }} {{ student.sexName }} {{ student.mobile }}
                  {{ student.birthDate }}
                </div>
							</div> -->
							<div class="select-students">
								<div v-if="selectedStudent" style="margin-bottom: 18px" class="custom-student">
									{{ selectedStudent.nameC }} {{ selectedStudent.sexName }}
									{{ selectedStudent.mobile }}
									{{ selectedStudent.birthDate }}
								</div>
							</div>
						</div>
						<!-- 请选择课程套餐 -->

						<div class="section" style="padding-top: 0">
							<div class="coursePackages" v-if="pageInfo.scheduleType === 2">
								<div class="package-select-title">{{ t('adminCourse.selectPackage') }}</div>
								<div v-if="saleConfigLoading" class="package-status">
									<el-icon class="is-loading">
										<Loading />
									</el-icon>
									<span>{{ t('courseBuy.selectStudent.loading') }}</span>
								</div>
								<div v-else-if="!saleConfigList.length" class="package-status">
									<span>{{ t('noDataAvailable') }}</span>
								</div>
								<div v-else class="package-cards">
									<div v-for="pkg in saleConfigList" :key="pkg.id" class="package-card"
										:class="{ selected: selectedSaleConfigId === Number(pkg.id) }" @click="handleSelectPackage(pkg)">
										<div class="selected-icon" v-if="selectedSaleConfigId === Number(pkg.id)">
											<svg-icon name="tick" class="svg-style"></svg-icon>
										</div>
										<div class="package-header">
											<span class="package-header-name">{{ pkg.name ?? '--' }}</span>
										</div>
										<ul class="package-details">
											<li v-for="feature in formatPackageFeatures(pkg)" :key="feature">
												<span class="check-icon" :class="{
													'check-icon-active': selectedSaleConfigId === Number(pkg.id),
												}">
													<svg-icon name="thickWire" class="svg-style"></svg-icon>
												</span>
												<span class="package-details-val">
													{{ feature }}
												</span>
											</li>
										</ul>
										<div class="package-price-details">
											<div class="price-item">
												<span>{{ t('adminCourse.packageCoursePrice') }}：</span>
												<span>{{ pkg.price ?? 0 }}{{ t('courseBuy.courseInfo.currency') }}</span>
											</div>
											<div class="price-item">
												<span>{{ t('adminCourse.packageRenewalPrice') }}：</span>
												<span class="renewal-price">{{ pkg.renewPrice ?? 0 }}{{ t('courseBuy.courseInfo.currency')
												}}</span>
											</div>
										</div>
									</div>
								</div>
							</div>
							<div class="section-title-payType">
								<div class="title">{{ t('adminCourse.paymentMethod') }}</div>
								<el-radio-group v-model="payType">
									<el-radio label="offline" class="section-type-text">
										{{ t('coursePay.methodOffline') }}
									</el-radio>
									<!-- <el-radio label="online" class="section-type-text">
                    线上付款
                  </el-radio> -->
								</el-radio-group>
								<div v-if="payType === 'online'" class="pay-channels">
									<div v-for="channel in payChannelList" :key="channel.value" class="custom-checkbox"
										:class="{ checked: payChannels.includes(channel.value) }" @click="toggleChannel(channel.value)">
										<span class="icon">
											<svg-icon v-if="payChannels.includes(channel.value)" name="is-select"
												class="svg-style"></svg-icon>
											<svg-icon v-else name="select" class="svg-style"></svg-icon>
										</span>
										<span class="label">{{ channel.label }}</span>
									</div>
								</div>
								<div v-if="payType === 'offline'" class="offline-payment-details">
									<div class="upload-label">{{ t('adminCourse.paymentUploadTip') }}</div>
									<el-upload :http-request="onReceiptUpload" :file-list="receiptFileList" list-type="picture-card"
										:auto-upload="true" :before-upload="beforeReceiptUpload" :on-remove="onReceiptRemove"
										accept="image/*">
										<el-icon>
											<Plus />
										</el-icon>
									</el-upload>
								</div>
							</div>
						</div>
						<!-- 立即付款按钮 -->
						<div class="payNow">
							<button v-if="payType === 'online'" class="pay-btn">{{ t('adminCourse.payNow') }}</button>
							<template v-if="payType === 'offline'">
								<div class="offline-btn">
									<el-tooltip :disabled="receiptFileList.length > 0" :content="t('courseBuy.payment.uploadRequiredTip')"
										placement="top">
										<span class="pay-btn-wrapper">
											<button class="pay-btn" @click="handleConfirmPayment(1)" v-loading="confirmedLoading"
												:disabled="saveLoading || confirmedLoading || receiptFileList.length === 0">
												{{ t('adminCourse.confirmPaid') }}
											</button>
										</span>
									</el-tooltip>
									<el-tooltip class="box-item" effect="dark" :content="t('adminCourse.saveOrderTip')"
										placement="bottom-end">
										<div>
											<button class="save-btn" @click="handleConfirmPayment(2)" v-loading="saveLoading"
												:disabled="saveLoading || confirmedLoading">
												{{ t('adminCourse.saveOrder') }}
											</button>
											<svg-icon name="exclamation" class="svg-style"></svg-icon>
										</div>
									</el-tooltip>
								</div>
							</template>
						</div>
					</div>

					<!-- 右侧课程信息 -->
					<div class="course-info">
						<img class="course-img" v-if="
							pageInfo.promotionalImages && pageInfo.promotionalImages.length > 0
						" :src="pageInfo.promotionalImages[0]" :alt="t('courseBuy.courseInfo.imageAlt')" />
						<div class="course-title">{{ pageInfo.courseName ?? '--' }}</div>
						<!-- <div class="course-desc">{{ course.desc }}</div> -->
						<div class="course-detail">
							<div>
								{{ t('courseBuy.courseInfo.applicableAge') }}：
								{{ t('courseDetail.ageUnit', { age: pageInfo.applicableAge ?? 0 }) }}
							</div>
							<div>
								{{ t('courseBuy.courseInfo.numberAttendees') }}：
								{{
									t('courseDetail.numberUnit', {
										count: pageInfo.coursePackageType == 0
											? pageInfo.numberAttendees ?? 0
											: `${pageInfo.minNumberAttendees ?? 0}-${pageInfo.maxNumberAttendees ?? 0}`,
									})
								}}
							</div>
							<div>{{ t('courseBuy.courseInfo.courseStartDate') }}： {{ formatDate(pageInfo.courseStartDate) ?? '--' }}
							</div>
							<div>
								{{ t('courseBuy.courseInfo.classCount') }}：
								{{
									$t('courseDetail.classHourUnit', {
										section: selectedCourseNumber,
										hours: convertMinutesToHours(selectedTimeEachClass),
									})
								}}
							</div>
							<div>{{ t('courseBuy.courseInfo.location') }}： {{ pageInfo.venueName ?? '--' }}</div>

							<div class="typeOfCourse">
								<span>{{ courseTypeText }}</span>
							</div>
						</div>
						<div class="price-detail">
							<div class="price-detail-title">{{ t('courseBuy.courseInfo.priceDetail') }}</div>
							<div class="price-row">
								<span class="price-row-title">{{ t('courseBuy.courseInfo.studentCount') }}：</span>
								<span class="price">{{ selectedStudentCount }}{{ t('courseBuy.courseInfo.personUnit') }}</span>
							</div>
							<div class="price-row">
								<span class="price-row-title">{{ t('courseBuy.courseInfo.coursePrice') }}：</span>
								<span class="price">{{ coursePrice ?? 0 }}{{ t('courseBuy.courseInfo.currency') }}</span>
							</div>
							<div class="price-row">
								<span class="price-row-title">{{ t('courseBuy.courseInfo.discountAmount') }}：</span>
								<span class="discount">-{{ discountAmount }}{{ t('courseBuy.courseInfo.currency') }}</span>
							</div>
							<div class="price-row">
								<span class="price-row-title">{{ t('courseBuy.courseInfo.totalPrice') }}：</span>
								<span class="total">{{ totalPrice ?? 0 }}{{ t('courseBuy.courseInfo.currency') }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- 选择学员· -->
	<el-dialog v-model="showStudentDialog" :title="t('courseBuy.selectStudent.dialogTitle')" width="720px" align-center
		:close-on-click-modal="false">
		<el-table :data="students" style="width: 100%" height="360" row-key="id" highlight-current-row
			:current-row-key="tempSelectedStudentId" @row-click="handleRowClick">
			<el-table-column width="80">
				<template #default="{ row }">
					<el-radio v-model="tempSelectedStudentId" :label="row.id" @change="() => handleStudentRadioChange(row)" />
				</template>
			</el-table-column>
			<el-table-column prop="nameC" :label="t('courseBuy.selectStudent.columns.name')" min-width="120" />
			<el-table-column prop="sexName" :label="t('courseBuy.selectStudent.columns.gender')" min-width="80" />
			<el-table-column prop="mobile" :label="t('courseBuy.selectStudent.columns.phone')" min-width="140" />
			<el-table-column prop="birthDate" :label="t('courseBuy.selectStudent.columns.birthday')" min-width="140" />
			<template #empty>
				<div v-if="studentTableLoading" style="padding: 40px 0">
					<el-icon class="is-loading">
						<Loading />
					</el-icon>
					<p style="margin-top: 10px">{{ t('courseBuy.selectStudent.loading') }}</p>
				</div>
				<div v-else style="padding: 40px 0">{{ t('courseBuy.selectStudent.empty') }}</div>
			</template>
		</el-table>
		<Pagination :background="true" :total="total" :current-page.sync="pageNum" :page-size.sync="pageSize"
			@pagination-change="paginationChange" class="pagination" />

		<template #footer>
			<div style="display: flex; gap: 24px; justify-content: center">
				<el-button type="primary" @click="addStudent"> {{ t('courseBuy.selectStudent.add') }} </el-button>
				<el-button type="primary" @click="confirmStudentSelection"> {{ t('courseBuy.selectStudent.confirm') }}
				</el-button>
				<el-button @click="cancelStudentSelection">{{ t('courseBuy.selectStudent.cancel') }}</el-button>
			</div>
		</template>
	</el-dialog>
	<el-dialog v-model="showAddStudent" :title="t('courseBuy.addStudent.title')" width="480px" align-center
		:close-on-click-modal="false" @close="handleCancel">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
			<el-form-item :label="t('courseBuy.addStudent.name')" prop="name">
				<el-input v-model="form.name" :placeholder="t('courseBuy.addStudent.namePlaceholder')" />
			</el-form-item>

			<el-form-item :label="t('courseBuy.addStudent.phone')" prop="phone">
				<el-input v-model="form.phone" :placeholder="t('courseBuy.addStudent.phonePlaceholder')" />
			</el-form-item>

			<el-form-item :label="t('courseBuy.addStudent.gender')" prop="gender">
				<el-radio-group v-model="form.gender">
					<el-radio label="1">{{ t('courseBuy.addStudent.male') }}</el-radio>
					<el-radio label="0">{{ t('courseBuy.addStudent.female') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item :label="t('courseBuy.addStudent.birthday')" prop="birthday">
				<el-date-picker v-model="form.birthday" type="date" value-format="YYYY-MM-DD"
					:placeholder="t('courseBuy.addStudent.birthdayPlaceholder')" style="width: 100%" />
			</el-form-item>
		</el-form>

		<template #footer>
			<div style="display: flex; gap: 24px; justify-content: center">
				<el-button type="primary" @click="handleSave" :loading="addBtnLoading">
					{{ t('courseBuy.addStudent.submit') }}
				</el-button>
				<el-button @click="handleCancel">{{ t('courseBuy.addStudent.cancel') }}</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import headerBg from '~/assets/web/activity-header-bg.png';
import { User, Plus } from '@element-plus/icons-vue';
import {
	GetCourseDetail,
	GetTeacherInfo,
	GetStudentList,
	AddStudent,
	UploadCourseOrder,
	priceCalculation,
	SaveOrder,
	GetSaleConfigList,
} from '~/apis/web';
import { ElMessage } from 'element-plus';
import { preciseMultiply, preciseSubtract } from '~/utils/utils';
const pageInfo = ref({});
const loading = ref(false);
const route = useRoute();
const router = useRouter();
const id = computed(() => route.query.id);
const { t } = useI18n();
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

const students = ref([]);
const addBtnLoading = ref(false);
const payType = ref('offline');
const payChannels = ref(['']);
const showAddStudent = ref(false);
const showStudentDialog = ref(false);
const studentTableLoading = ref(false);
const selectedStudent = ref(null);
const tempSelectedStudent = ref(null);
const tempSelectedStudentId = ref('');
const saleConfigList = ref([]);
const saleConfigLoading = ref(false);
const selectedSaleConfigId = ref(null);
const selectedSaleConfig = computed(() =>
	saleConfigList.value.find(item => String(item.id) === String(selectedSaleConfigId.value))
);
const selectedCourseNumber = computed(
	() => selectedSaleConfig.value?.courseNumber ?? pageInfo.value?.customCourseTime?.courseNumber ?? 0
);
const selectedTimeEachClass = computed(
	() => selectedSaleConfig.value?.timeEachClass ?? pageInfo.value?.customCourseTime?.timeEachClass ?? 0
);

const receiptFileList = ref([]); // el-upload 受控列表，存 url/name 等
const receiptUrls = ref([]); // 保存上传后返回的 url 或 id，供后续提交使用
const selectedStudentCount = computed(() => {
	return selectedStudent.value ? 1 : 0;
});

const discountAmount = ref(0); // 优惠金额
const userStore = useStore.userStore();
// 课程价格
const coursePrice = ref(0);
const totalPrice = computed(() => {
	const basePrice = preciseMultiply(coursePrice.value, selectedStudentCount.value);
	return preciseSubtract(basePrice, discountAmount.value);
});

const form = ref({
	name: '',
	phone: '',
	gender: '',
	birthday: '',
});
const rules = computed(() => ({
	name: [{ required: true, message: t('courseBuy.addStudent.rules.name'), trigger: 'blur' }],
	phone: [
		{ required: true, message: t('courseBuy.addStudent.rules.phone'), trigger: 'blur' },
		{
			pattern: /^[\+]?[1-9][\d\s\-\(\)]{5,19}$/,
			message: t('courseBuy.addStudent.rules.phoneInvalid'),
			trigger: 'blur',
		},
	],
}));

const payChannelOptions = [
	{ value: 'wechat' },
	{ value: 'alipay' },
	{ value: 'alipayhk' },
	{ value: 'cup' },
	{ value: 'visa' },
	{ value: 'payme' },
	{ value: 'transfer' },
];
const payChannelList = computed(() =>
	payChannelOptions.map(channel => ({
		...channel,
		label: t(`adminCourse.payChannel.${channel.value}`),
	}))
);
const formRef = ref(null);

function toggleChannel(val) {
	const idx = payChannels.value.indexOf(val);
	if (idx > -1) {
		payChannels.value.splice(idx, 1);
	} else {
		payChannels.value.push(val);
	}
}

const formatPackageFeatures = pkg => {
	const features = [];
	const classNumber = pkg?.courseNumber ?? 0;
	const timeEachClass = pkg?.timeEachClass ?? 0;
	const effectiveDays = pkg?.effectiveDays ?? 0;

	features.push(
		t('courseDetail.classHourUnit', {
			section: classNumber,
			hours: convertMinutesToHours(timeEachClass),
		})
	);

	if (effectiveDays) {
		features.push(t('adminCourse.package.features.validityDays', { days: effectiveDays }));
	}

	return features;
};

const applySaleConfigInfo = pkg => {
	selectedSaleConfigId.value = pkg?.id ? Number(pkg.id) : null;
	coursePrice.value = pkg?.price ?? 0;
	pageInfo.value.customCourseTime = {
		...(pageInfo.value.customCourseTime || {}),
		courseNumber: pkg?.courseNumber ?? pageInfo.value?.customCourseTime?.courseNumber ?? 0,
		timeEachClass: pkg?.timeEachClass ?? pageInfo.value?.customCourseTime?.timeEachClass ?? 0,
		effectiveDays: pkg?.effectiveDays ?? pageInfo.value?.customCourseTime?.effectiveDays,
	};
	discountAmount.value = 0;
};

const handleSelectPackage = pkg => {
	if (!pkg) return;
	applySaleConfigInfo(pkg);
	getCoursePrice(pkg.id);
};

const loadSaleConfigs = async ids => {
	if (pageInfo.value.scheduleType !== 2) return;
	saleConfigLoading.value = true;
	try {
		const idList = (ids || []).filter(Boolean);
		if (!idList.length) {
			saleConfigList.value = [];
			selectedSaleConfigId.value = null;
			coursePrice.value = 0;
			return;
		}
		const res = await GetSaleConfigList({ saleType: 1 });
		if (res.code === 0) {
			const idSet = new Set(idList.map(id => Number(id)));
			const list = res.data || [];
			const filtered = idSet.size ? list.filter(item => idSet.has(Number(item.id))) : list;
			saleConfigList.value = filtered;
			if (filtered.length > 0) {
				handleSelectPackage(filtered[0]);
			} else {
				coursePrice.value = 0;
				selectedSaleConfigId.value = null;
			}
		} else {
			saleConfigList.value = [];
		}
	} catch (error) {
		saleConfigList.value = [];
		selectedSaleConfigId.value = null;
	} finally {
		saleConfigLoading.value = false;
	}
};

const { courseTypeLabel } = useCourseLabel();
const courseTypeText = computed(() => courseTypeLabel(pageInfo.value?.courseType));

// 将分钟转换为小时的函数
const convertMinutesToHours = (minutes) => {
	if (!minutes || minutes === 0) return 0;
	return (minutes / 60).toFixed(1);
};

const confirmedLoading = ref(false);
const saveLoading = ref(false);

const handleShowStudents = () => {
	tempSelectedStudentId.value = selectedStudent.value?.id ?? '';
	tempSelectedStudent.value = selectedStudent.value;
	showStudentDialog.value = true;
	// 获取学员列表
	getStudentList();
};

/**
 * 
 * @param index 1: 确认已付款 2: 仅保存订单
 * @returns {
 * 	code: 0,
 * 	msg: '操作成功',
 * 	data: {
 * 		orderId: '1234567890',
 * 	},
 * }
 */
const handleConfirmPayment = index => {
	const studentList = [];
	if (selectedStudent.value) {
		studentList.push({
			id: '',
			orderId: '',
			courseId: id.value,
			studentId: selectedStudent.value.id,
		});
	}
	const targetSaleConfigId =
		selectedSaleConfigId.value ??
		pageInfo.value?.courseConfigRespVO?.courseSaleConfigRespVOS?.[0]?.saleConfigId;

	if (!targetSaleConfigId) {
		ElMessage.warning(t('adminCourse.selectPackage'));
		return;
	}
	let params = {
		courseId: id.value,
		userId: userStore.user.id,
		numberOfCourseParticipants: selectedStudentCount.value,
		price: coursePrice.value,
		preferentialPrice: discountAmount.value,
		totalPayableAmount: totalPrice.value,
		payWay: 1,
		studentList: studentList,
		receiptRecord: receiptUrls.value.join(','),
		saleConfigId: targetSaleConfigId,
	};
	if (index == 1) {
		// 确认已付款
		confirmedLoading.value = true;
	} else if (index == 2) {
		saveLoading.value = true;
		params.receiptRecord = '';
		params.justSave = 1
	}
	SaveOrder(params)
		.then(res => {
			if (res.code == 0) {
				ElMessage.success(t('courseBuy.payment.actionSuccess'));
				if (index === 1) {
					const payInfoQuery = {
						paymentMethod: payType.value,
						orderNo: res?.data?.orderId ?? res?.data?.id ?? '',
						paidAt: res?.data?.paymentTime ?? new Date().toISOString(),
					};
					router.push({
						path: '/web/courses/payType',
						query: payInfoQuery,
					});
				}
			}
		})
		.catch(() => { })
		.finally(() => {
			confirmedLoading.value = false;
			saveLoading.value = false;
		});
};

const handleSave = () => {
	addBtnLoading.value = true;
	formRef.value?.validate(valid => {
		if (!valid) return;
		// TODO: 提交保存 form.value
		console.log('-----', form);
		let params = {
			id: '',
			userId: userStore.user.id,
			nameC: form.value.name,
			age: '',
			mobile: form.value.phone,
			sex: form.value.gender,
			birthDate: form.value.birthday,
			notes: '',
		};

		AddStudent(params)
			.then(res => {
				console.log('添加学院成功', res);
				if (res.code == 0) {
					ElMessage.success(t('courseBuy.addStudent.success'));
					showAddStudent.value = false;
					getStudentList();
					addBtnLoading.value = false;
				}
			})
			.catch(error => {
				addBtnLoading.value = false;
			});
		// showAddStudent.value = false;
	});
};

const handleCancel = () => {
	formRef.value?.resetFields();
	showAddStudent.value = false;
};

const getReacherInfo = async params => {
	try {
		const res = await GetTeacherInfo({ id: params.staffId });
		if (res.code === 0) {
			return res.data;
		}
		return null;
	} catch (err) {
		return null;
	}
};

const handleStudentRadioChange = row => {
	tempSelectedStudent.value = row;
};

const handleRowClick = row => {
	tempSelectedStudentId.value = row.id;
	tempSelectedStudent.value = row;
};

const addStudent = () => {
	showAddStudent.value = true;
};

const confirmStudentSelection = () => {
	selectedStudent.value = tempSelectedStudent.value;
	showStudentDialog.value = false;
};
const cancelStudentSelection = () => {
	tempSelectedStudentId.value = selectedStudent.value?.id ?? '';
	tempSelectedStudent.value = selectedStudent.value;
	showStudentDialog.value = false;
};
// 获取课程价格

const getCoursePrice = params => {
	return priceCalculation({ id: params }).then(res => {
		console.log('获取课程价格', res);
		if (res.code == 0) {
			coursePrice.value = res.data.price ?? 0;
			pageInfo.value.customCourseTime = {
				...(pageInfo.value.customCourseTime || {}),
				courseNumber: res.data.courseNumber ?? pageInfo.value?.customCourseTime?.courseNumber ?? 0,
				timeEachClass: res.data.timeEachClass ?? pageInfo.value?.customCourseTime?.timeEachClass ?? 0,
				effectiveDays: res.data.effectiveDays ?? pageInfo.value?.customCourseTime?.effectiveDays,
			};
		}
		return res;
	});
};

const init = async () => {
	let params = {
		id: id.value,
	};
	loading.value = true;

	try {
		const res = await GetCourseDetail(params);
		if (res.code == 0) {
			let thearInfo = res.data.courseTeacherConsultantRespVOS?.filter(item => item.type == 0) || [];

			const teacherInfo = thearInfo.length ? await getReacherInfo(thearInfo[0]) : null;

			res.data.teacherInfo = teacherInfo;
			pageInfo.value = res.data;

			const saleConfigIds =
				res.data?.courseConfigRespVO?.courseSaleConfigRespVOS?.map(item => item.saleConfigId).filter(Boolean) || [];

			await loadSaleConfigs(saleConfigIds);

			if (pageInfo.value.scheduleType !== 2 && saleConfigIds.length > 0) {
				await getCoursePrice(saleConfigIds[0]);
			}
		}
	} catch (err) {
		pageInfo.value = {};
	} finally {
		loading.value = false;
	}
};

const paginationChange = async val => {
	pageNum.value = val.currentPage;
	pageSize.value = val.pageSize;
	getStudentList();
};

const syncTempSelectedStudent = () => {
	if (!tempSelectedStudentId.value) return;
	const matched = students.value.find(item => item.id === tempSelectedStudentId.value);
	if (matched) {
		tempSelectedStudent.value = matched;
	}
};

const getStudentList = async () => {
	console.log('userStore', userStore.user.id);
	studentTableLoading.value = true; // 开始加载
	students.value = [];
	let params = {
		pageNo: pageNum.value,
		pageSize: pageSize.value,
		userId: userStore.user.id,
	};
	const res = await GetStudentList(params);
	if (res.code == 0) {
		res.data.list.forEach(item => {
			item.sexName = item.sex == 1 ? t('courseBuy.gender.male') : t('courseBuy.gender.female');
		});
		students.value = res.data.list;
		total.value = Number(res.data.total) || 0;
		console.log('学员列表res.data.list', students.value);

		syncTempSelectedStudent();
		studentTableLoading.value = false; // 结束加载
	}
};

// 上传相关
const beforeReceiptUpload = file => {
	const isImg = /^image\//.test(file.type);
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isImg) ElMessage.error(t('courseBuy.payment.uploadImageOnly'));
	if (!isLt10M) ElMessage.error(t('courseBuy.payment.uploadSizeLimit'));
	return isImg && isLt10M;
};

const onReceiptUpload = async option => {
	const formData = new FormData();
	formData.append('file', option.file); // 后端字段名通常是 'file'

	try {
		const res = await UploadCourseOrder(formData);
		if (res.code === 0) {
			// 兼容后端可能返回的不同结构（url / path / id）
			const data = res.data;
			const url = data?.url || data?.path || data?.fileUrl || data; // 根据你后端返回调整
			receiptUrls.value.push(url);
			option.onSuccess(data, option.file);

			// 同步 el-upload 的展示列表
			receiptFileList.value = [...receiptFileList.value, { name: option.file.name, url }];
		} else {
			option.onError(new Error(res.msg || t('courseBuy.payment.uploadFailed')));
		}
	} catch (e) {
		option.onError(e);
	}
};

const onReceiptRemove = (file, fileList) => {
	receiptFileList.value = fileList;
	// 同步移除对应的 url（按 url 匹配）
	if (file.url) {
		receiptUrls.value = receiptUrls.value.filter(u => u !== file.url);
	}
};

onMounted(() => {
	init();
});
</script>

<style lang="less">
/* 放大选中圆圈和对勾 */
.section .el-radio__inner {
	width: 24px !important;
	height: 24px !important;
	border-radius: 50%;
	border-width: 2px;
}

/* 选中时绿色背景 */
.section .el-radio.is-checked .el-radio__inner {
	background: #2b7a6b;
	border-color: #2b7a6b;
	position: relative;
}

/* 选中时显示大号对勾 */
.section .el-radio.is-checked .el-radio__inner::after {
	content: '';
	display: block;
	width: 20px;
	height: 20px;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	background: url('data:image/svg+xml;utf8,<svg fill="white" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M6.173 13.727a.75.75 0 0 1-1.06 0l-3.84-3.84a.75.75 0 1 1 1.06-1.06l3.31 3.31 7.07-7.07a.75.75 0 0 1 1.06 1.06l-7.6 7.6z"/></svg>');
	background-size: 16px 16px;
	background-repeat: no-repeat;
	background-position: center;
}

/* 未选中时不显示对勾 */
.section .el-radio__inner::after {
	content: none;
}

.section-type-text .el-radio__label {
	font-family: PingFang HK, PingFang HK;
	font-weight: 600;
	font-size: 18px;
	color: #1e2021 !important;
	line-height: 24px;
	text-align: left;
	font-style: normal;
	text-transform: none;
	display: inline-flex;
	align-items: center;
	justify-content: flex-start;
}
</style>

<style lang="less" scoped>
.el-tooltip {
	inset: 20px 30px auto auto !important;
}

.buy {
	width: 100%;
	margin-bottom: 110px;

	.content {
		width: 100%;
		padding: 30px 104px;
		box-sizing: border-box;
		margin: 0 auto;

		.content_detail {
			width: 100%;
			padding: 30px 100px;
			box-sizing: border-box;
			background-color: #ffffff;
			border-radius: 10px;
		}

		.title {
			font-family: PingFang HK, PingFang HK;
			font-weight: 600;
			font-size: 32px;
			color: #1e2021;
			margin-bottom: 30px;
		}

		.main {
			width: 100%;
			display: flex;
			justify-content: center;

			.order-info {
				display: flex;
				flex-direction: column;
				flex: 1;
				margin-right: 30px;

				.section {
					padding: 24px;
					box-sizing: border-box;

					.section-title-row {
						display: flex;
						align-items: center;
						justify-content: flex-start;
						margin-bottom: 40px;

						.section-title {
							font-family: PingFang HK, PingFang HK;
							font-weight: 500;
							font-size: 20px;
							color: #1e2021;
							margin-right: 20px;
						}
					}

					.section-title-payType {
						width: 100%;

						.title {
							font-family: PingFang HK, PingFang HK;
							font-weight: 500;
							font-size: 20px;
							color: #1e2021;
							margin-bottom: 48px;
						}

						.pay-channels {
							display: flex;
							flex-wrap: wrap;
							gap: 16px;
							margin-top: 16px;

							.custom-checkbox {
								display: flex;
								align-items: center;
								cursor: pointer;
								padding: 8px 16px;
								box-sizing: border-box;
								border-radius: 6px;
								background: #fff;
								transition: border-color 0.2s;

								.icon {
									font-size: 24px;
									margin-right: 8px;
									display: flex;
									align-items: center;
									justify-content: center;
								}

								.label {
									font-family: PingFang HK, PingFang HK;
									font-weight: 600;
									font-size: 14px;
									color: #1e2021;
								}

								&.checked {
									border-color: #2b7a6b;
									background: #f0f9f4;
									// .label {
									//     color: #2b7a6b;
									// }
								}
							}
						}

						.offline-payment-details {
							margin-top: 24px;

							.upload-label {
								font-size: 14px;
								color: #656c7e;
								margin-bottom: 16px;
							}
						}
					}

					.coursePackages {
						.package-select-title {
							font-weight: bold;
							font-size: 18px;
							margin-bottom: 18px;
						}

						.package-cards {
							display: flex;
							flex-wrap: wrap;
							gap: 24px;
							margin-bottom: 32px;

							.package-card {
								padding: 18px 24px;
								box-sizing: border-box;
								width: 220px;
								cursor: pointer;
								background: #fff;
								transition: border-color 0.2s, box-shadow 0.2s;
								position: relative;
								border-radius: 2px 2px 2px 2px;
								border: 1px solid #000000;
								overflow: hidden;

								.selected {
									border: 1px solid #000000;
								}

								.selected-icon {
									position: absolute;
									top: 2px;
									right: 4px;
									z-index: 1;

									.svg-style {
										font-size: 15px;
										color: #ffffff;
									}
								}

								.package-header {
									display: flex;
									justify-content: flex-start;
									align-items: center;

									.package-header-name {
										font-family: Inter, Inter;
										font-weight: 400;
										font-size: 16px;
										color: #071430;
									}

									.discount {
										flex: 1;
										position: relative;
										margin-left: 10px;

										img {
											width: 63px;
											position: absolute;
											left: 0;
											top: 50%;
											transform: translateY(-50%);
										}

										.percentage {
											font-family: Inter, Inter;
											font-weight: 400;
											font-size: 16px;
											color: #ffffff;
											position: absolute;
											left: 20px;
											z-index: 1;
											top: 50%;
											transform: translateY(-50%);
										}
									}
								}

								.package-price {
									margin: 10px 0;
									font-family: Inter, Inter;
									font-weight: bold;
									font-size: 40px;
									color: #1e2021;
								}

								.package-details {
									list-style: none;
									padding: 0;
									margin: 18px 0;

									li {
										margin-bottom: 20px;
										display: flex;

										.check-icon {
											width: 20px;
											height: 20px;
											background: #e2e2e2;
											border-radius: 50%;
											text-align: center;
											margin-right: 10px;

											.svg-style {
												font-size: 10px;

												color: #2d3436;
											}
										}

										.check-icon-active {
											background: #202d48;

											.svg-style {
												color: #ffffff;
											}
										}

										.package-details-val {
											font-family: Inter, Inter;
											font-weight: 400;
											font-size: 14px;
											color: #1e2021;
										}
									}
								}

								.package-price-details {
									font-family: Inter, Inter;
									font-weight: 400;
									font-size: 12px;
									color: #656c7e;

									.price-item {
										margin-bottom: 10px;
									}

									.renewal-discount {
										color: #d03720;
										margin-left: 4px;
									}
								}
							}

							/* 为未选中的卡片添加线框三角形 */
							.package-card:not(.selected)::after {
								content: '';
								position: absolute;
								width: 56px;
								height: 56px;
								top: -28px;
								right: -28px;
								transform: rotate(45deg);
								box-shadow: 0 0 0 1px #000;
								/* 确保伪元素不会有从 .package-card.selected::after 继承的非预期样式 */
								border-style: none;
							}

							/* 选中的卡片使用实心三角形 */
							.package-card.selected::after {
								content: '';
								position: absolute;
								top: 0;
								right: 0;
								width: 0;
								height: 0;
								border-style: solid;
								border-width: 0 40px 40px 0;
								border-color: transparent #000000 transparent transparent;
								/* 重置从未选中状态继承的样式 */
								transform: none;
								box-shadow: none;
							}
						}

						.package-status {
							display: flex;
							align-items: center;
							gap: 8px;
							color: #656c7e;
							min-height: 80px;
						}
					}
				}

				.payNow {
					width: 100%;
					padding-bottom: 30px;
					box-sizing: border-box;

					.pay-btn-wrapper {
						display: inline-block;
					}

					.pay-btn {
						padding: 15px 63px;
						box-sizing: border-box;
						font-family: PingFang HK, PingFang HK;
						font-weight: 500;
						font-size: 16px;
						color: #fcfcfd;
						background: var(--theme-gradient-bg);
						border: none;
						cursor: pointer;

						&:disabled {
							cursor: not-allowed !important;
							opacity: 0.6;
						}
					}

					.offline-btn {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.save-btn {
							padding: 15px 63px;
							box-sizing: border-box;
							font-family: PingFang HK, PingFang HK;
							font-weight: 500;
							font-size: 16px;
							color: #1e2021;
							background-color: #fff;
							border: 1px solid #dcdfe6;
							cursor: pointer;
							margin-right: 10px;

							// 添加禁用状态样式
							&:disabled {
								cursor: not-allowed !important;
								opacity: 0.6; // 可选：添加透明度效果
							}
						}
					}
				}
			}

			.course-info {
				width: calc(100vw * 418 / 1440);
				flex: none;
				padding: 24px;
				box-sizing: border-box;
				background: #fcfcfd;
				border-radius: 0px 0px 0px 0px;
				border: 1px solid #e9ebed;

				.course-img {
					width: 100%;
					aspect-ratio: 370 / 262;
					height: auto;
					object-fit: cover;
					border-radius: 8px;
				}

				.course-title {
					font-family: PingFang HK, PingFang HK;
					font-weight: 600;
					font-size: 16px;
					color: #1e2021;
					margin: 24px 0 10px 0;
				}

				// .course-desc {
				//     color: #888;
				//     margin-bottom: 12px;
				// }

				.course-detail {
					margin-bottom: 24px;
					font-family: PingFang HK, PingFang HK;
					font-weight: 400;
					font-size: 14px;
					color: #656c7e;

					div {
						margin-bottom: 10px;
					}

					.typeOfCourse {
						width: 100%;
						margin-top: 15px;

						span {
							padding: 6px 15px;
							box-sizing: border-box;
							background: #2b3339;
							border-radius: 0px 0px 0px 0px;
							font-family: PingFang HK, PingFang HK;
							font-weight: 500;
							font-size: 12px;
							color: #ffffff;
						}
					}
				}

				.price-detail {
					.price-detail-title {
						font-family: PingFang HK, PingFang HK;
						font-weight: 600;
						font-size: 16px;
						color: #09080d;
						margin-bottom: 28px;
					}

					.price-row {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 28px;
						font-family: PingFang HK, PingFang HK;
						font-weight: 500;
						font-size: 16px;
						color: #1e2021;

						.price-row-title {
							font-family: PingFang HK, PingFang HK;
							font-weight: 500;
							font-size: 16px;
							color: #656c7e;
						}

						.price,
						.discount {
							color: #1e2021;
						}

						.total {
							color: #ec4613;
						}
					}
				}
			}
		}
	}
}

.student-list {
	.student-item {
		font-family: PingFang HK, PingFang HK;
		font-size: 14px;
		color: #1e2021;
	}
}

.custom-student {
	background: #fcfcfd;
	border-radius: 0px 0px 0px 0px;
	border: 1px solid #e9ebed;
	padding: 20px 25px;
	box-sizing: border-box;
	height: auto;
	width: 100%;
}

// :deep(.el-checkbox.is-checked .el-checkbox__inner) {
//   background-color: #226f41 !important;
//   border-color: #226f41 !important;
// }

// :deep(.el-checkbox.is-checked .el-checkbox__label) {
//   color: #1e2021 !important;
// }</style>
